import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    cart: []
  },
  getters: {
    totalPrice: state => {
      return state.cart.reduce((total, item) => {
        return total + (item.price * item.quantity);
      }, 0);
    }
  },
  mutations: {
    addToCart(state, item) {
      const cartItem = state.cart.find(i => i.id === item.id);
      if (cartItem) {
        cartItem.quantity++;
      } else {
        state.cart.push({ ...item, quantity: 1 });
      }
    },
    removeFromCart(state, item) {
      const cartItem = state.cart.find(i => i.id === item.id);
      if (cartItem) {
        if (cartItem.quantity > 1) {
          cartItem.quantity--;
        } else {
          state.cart = state.cart.filter(i => i.id !== item.id);
        }
      }
    }
  }
});